<?php
namespace App\Services;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use Framework\BaseService;
use Framework\Hope;

class HttpService extends BaseService
{

    /** 阿里短信配置
     * @param string $phone
     * @param string $code
     * @return bool
     * @throws ClientException
     */
    public function sendSms(string $phone, string $code)
    {
        if(!Hope::isProduct()){
            return true;
        }
        $accessKey = env('ALIYUN_SMS_ACCESS_KEY', 'LTAI5tNa9zoaLVY7K7Q5pHeM');
        $secretKey = env('ALIYUN_SMS_ACCESS_SECRET', 'mKgAWOg3hR0TTObvCjNCVmBt04R7az');
        $query = [
            'PhoneNumbers'  => $phone,
            'SignName'      => env('ALIYUN_SMS_SIGN_NAME', '国泓惠民'),
            'TemplateCode'  => env('ALIYUN_SMS_SEND_CODE', 'SMS_218580395'),
            'TemplateParam' => json_encode(['code' => $code]),
        ];
        AlibabaCloud::accessKeyClient($accessKey, $secretKey)
            ->regionId('cn-hangzhou')
            ->asDefaultClient();
        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                ->scheme('https')
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options([
                    'query' => $query
                ])
                ->request();
        } catch (ClientException $e) {
            $this->retError("短信发送失败");
        } catch (ServerException $e) {
            $this->retError("短信发送失败");
        }
        $result = $result->toArray();
        if ($result['Code'] == 'OK') {
            return true;
        } else {
            $this->retError("短信发送失败");
        }
    }


    /**
     * 腾讯短信
     * @param string $phone
     * @param string $code
     * @param string $type
     * @return bool|void
     */
    public function TencentsendSms(string $phone, string $code,string $type)
    {
        if(!Hope::isProduct()){
            return true;
        }
        $SecretId = config('sms.tencent_sms.secret_id');
        $SecretKey = config('sms.tencent_sms.secret_key');

        try {

            $cred = new Credential($SecretId, $SecretKey);

            $httpProfile = new HttpProfile();

            $httpProfile->setEndpoint("sms.tencentcloudapi.com");

            $clientProfile = new ClientProfile();
//            $clientProfile->setSignMethod("TC3-HMAC-SHA256");  // 指定签名算法(默认为HmacSHA256)
            $clientProfile->setHttpProfile($httpProfile);

            //类型 1=注册 2=登录  3=重置密码
            switch($type){
                case 1:
                    $template_id =  config('sms.tencent_sms.msg_register', '1444457');
                    break;
                case 2:
                    $template_id =  config('sms.tencent_sms.msg_login', '1354546');
                    break;
                case 3:
                    $template_id =  config('sms.tencent_sms.msg_forget_pass', '1354551');
                    break;
                default:
                    $this->retError('短信类型暂不支持');
            }

            $client = new SmsClient($cred, "ap-guangzhou", $clientProfile);
            $reqSms = new SendSmsRequest();
            if($type == 2){
                $TemplateParamSet = [$code,'2'];
            }else{
                $TemplateParamSet = [$code];
            }
            $params = array(
                "PhoneNumberSet" => array(
                    $phone
                ),
                "SmsSdkAppId" => config('sms.tencent_sms.sms_sdk_app_id','1400655336'),
                "TemplateId" => $template_id,
                "SignName" => config('sms.tencent_sms.sign_name','善水静柔'),
                "TemplateParamSet" =>$TemplateParamSet
            );

            $reqSms->fromJsonString(json_encode($params));

            $resp = $client->SendSms($reqSms);
            $resp = $resp->toJsonString();//回调信息是一个对象转换为json字符串
            $resp = json_decode($resp,true);//json字符串转换为数组

            $resp = $resp['SendStatusSet'][0];//获取状态信息
            if(($resp['Code']=="Ok") && ($resp['Message']=="send success"))
            {
                return true;
            } else {
                $this->retError("短信发送失败");
            }

        }catch(TencentCloudSDKException $e) {
            $this->retError("短信发送失败");
        }catch (ServerException $e) {
            $this->retError("短信发送失败");
        }
    }
}
